package com.example.user1.util;

import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.time.Duration;
import java.util.concurrent.TimeUnit;

@Component
@RequiredArgsConstructor
public class RedisImageCaptchaUtil implements CaptchaUtil{
    private final HttpServletResponse httpServletResponse;
    private final RedissonClient redissonClient;
    private final static String VERiFIY_CODE_PATH = "verifiy_code_path:image:";
    @Override
    public String getCaptcha(Long clientId) {
        return (String) redissonClient.getBucket(VERiFIY_CODE_PATH + clientId).getAndExpire(Duration.ofSeconds(1));
    }

    @Override
    public void generator(Long clientId, int codeSize) {
        try {
            String code = GenerateCode.outputVerifyImage(400, 200, httpServletResponse.getOutputStream(), codeSize);
            redissonClient.getBucket(VERiFIY_CODE_PATH + clientId).set(code,30, TimeUnit.SECONDS);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
